'use strict';
/*
To enable the initializer feature (https://help.aliyun.com/document_detail/156876.html)
please implement the initializer function as below：
exports.initializer = (context, callback) => {
  console.log('initializing');
  callback(null, '');
};
*/
var mysql = require('mysql');
var http = require('https');
const { connect } = require('tls');
var connection = mysql.createConnection({
    host: '.mysql.rds.aliyuncs.com',
    port: 3306,
    user: '',
    password: '',
    database: ''
});

connection.connect();


var nodemailer = require('nodemailer');
// create reusable transporter object using SMTP transport
var transporter = nodemailer.createTransport({
    "host": "smtpdm.aliyun.com",
    "port": 80,
    //"secureConnection": true, // use SSL, the port is 465
    "auth": {
        "user": '', // user name
        "pass": ''         // password
    }
});
exports.handler = (event, context, callback) => {
    var option = {
        "hostname": 'www.zhihu.com',
        "path": "/people/zhihu_question_shop/asks",
        headers: {
            "Content-Type": " application/x-www-form-urlencoded;charset=UTF-8",
            "Host": " www.zhihu.com",
            "User-Agent": " Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
            "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
            "Connection": "close",
            "Cookie": ""
        }
    };

    http.get(option, function (res) {
        var html = '';
        res.on('data', function (data) {
            html += data;
        });
        res.on('end', function () {
            var pattern = /questionCount\":-?[1-9]\d*/;
            var a = pattern.exec(html);
            var n = /-?[1-9]\d*/.exec(a);
            console.log(n[0]);
            var modsql = "SELECT `count` FROM `zhihuquestion` WHERE id= ?"
            var modSqlParams = ['zhihu_question_shop'];
            connection.query(modsql, modSqlParams, function (err, result) {
                if (err) {
                    console.log('[SELECT ERROR] - ', err.message);
                    return;
                }
                console.log(result[0]['count']);
                if (n[0] > result[0]['count']) {

                    var questionlinkpatter = /\"List-item\".*?\"QuestionItem-title\".*?href="(.*?)\"/;
                    var questionlink =questionlinkpatter.exec(html);

                    modsql = "UPDATE zhihuquestion SET count = ?,lastquestionlink = ? WHERE Id = ?"
                    modSqlParams = [n[0], questionlink[1], 'zhihu_question_shop']
                    connection.query(modsql, modSqlParams, function (err, result) {
                        if (err) {
                            console.log('[UPDATE ERROR] - ', err.message);
                            return;
                        }
                        console.log('--------------------------UPDATE----------------------------');
                        console.log('UPDATE affectedRows', result.affectedRows);
                        console.log('-----------------------------------------------------------------\n\n');

                        var mailOptions = {
                            from: 'yourboss@mail.com', // sender address mailfrom must be same with the user
                            to: '123456@qq.com', // list of receivers
                            subject: 'Hello', // Subject line
                            text: 'Hello world', // plaintext body
                            html: 'www.zhihu.com'+questionlink[1], // html body
                        };

                        transporter.sendMail(mailOptions, function(error, info){
                            if(error){
                                return console.log(error);
                            }
                            console.log('Message sent: ' + info.response);
                            callback(null, result.affectedRows);
                        });
                        
                    })
                } else {
                    callback(null, "");
                }
            });

        });
    });
}